<template>
    <div class="chat-container">
        <h1>用户与客服对话</h1>

        <!-- 聊天记录 -->
        <div class="messages-container">
            <div v-for="(msg, index) in messages" :key="index" class="message">
                <!-- 系统消息 -->
                <p v-if="msg.type === 'system'" class="system-message">
                    [系统] {{ msg.content }}
                </p>

                <!-- 用户消息 -->
                <p v-else-if="msg.user_id === user_id" class="user-message">
                    [我]: {{ msg.content }}
                </p>

                <!-- 客服消息 -->
                <p v-else class="kefu-message">
                    [{{ msg.user_id }}]: {{ msg.content }}
                </p>
            </div>
        </div>

        <!-- 输入框和发送按钮 -->
        <div class="input-container">
            <input v-model="input" type="text" placeholder="请输入您的消息..." @keyup.enter="sendMessage" />
            <button @click="sendMessage">发送</button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";

const messages = ref([]); // 用于存储聊天记录
const input = ref(""); // 用户输入的消息
const user_id = "user_1"; // 当前用户的唯一标识 (需要动态生成或从后端获取)
let socket = null; // WebSocket 实例

// 发送消息到 WebSocket
const sendMessage = () => {
    if (input.value.trim() === "") return;

    // 发送用户输入的消息到后端 WebSocket
    socket.send(
        JSON.stringify({
            message: input.value,
        })
    );

    // 本地展示发送的消息
    messages.value.push({
        user_id,
        content: input.value,
        type: "chat",
    });

    input.value = ""; // 清空输入框
};

// WebSocket 连接处理
onMounted(() => {
    // 创建 WebSocket 连接，连接到后端 WebSocket 消费者
    socket = new WebSocket(`ws://127.0.0.1:8000/ws/chat/${user_id}/`);

    // 接收来自 WebSocket 的消息
    socket.onmessage = (event) => {
        const data = JSON.parse(event.data);

        // 系统消息处理
        if (data.system_message) {
            messages.value.push({
                type: "system",
                content: data.system_message,
            });
        }

        // 聊天消息处理
        if (data.message) {
            messages.value.push({
                type: "chat",
                user_id: data.user_id,
                content: data.message,
            });
        }
    };

    // 监听 WebSocket 关闭事件
    socket.onclose = () => {
        messages.value.push({
            type: "system",
            content: "WebSocket 连接已关闭。",
        });
    };

    // 监听 WebSocket 错误事件
    socket.onerror = (error) => {
        console.error("WebSocket 连接出错:", error);
        messages.value.push({
            type: "system",
            content: "WebSocket 连接出错。",
        });
    };
});

// 清理 WebSocket 连接
onBeforeUnmount(() => {
    if (socket) {
        socket.close();
    }
});
</script>

<style scoped>
/* 样式 */
.chat-container {
    display: flex;
    flex-direction: column;
    max-width: 600px;
    margin: 0 auto;
    border: 1px solid #ccc;
    padding: 16px;
    border-radius: 8px;
    background: #f9f9f9;
}

.messages-container {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 16px;
    max-height: 400px;
    border: 1px solid #ccc;
    padding: 8px;
    border-radius: 8px;
    background: #fff;
}

.message {
    margin-bottom: 8px;
}

.system-message {
    color: gray;
    font-style: italic;
}

.user-message {
    color: blue;
}

.kefu-message {
    color: green;
}

.input-container {
    display: flex;
    gap: 8px;
}

input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

button {
    padding: 8px 16px;
    border: none;
    background: #007bff;
    color: white;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background: #0056b3;
}
</style>
